package cn.zhangfusheng.elasticsearch.setting;

import cn.zhangfusheng.elasticsearch.constant.ElasticSearchConstant;
import cn.zhangfusheng.elasticsearch.exception.GlobalSystemException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author fusheng.zhang
 * @date 2022-07-27 14:45:25
 */
public class SettingJsonConfig {

    private final Map<String, String> cache = new HashMap<>();

    public SettingJsonConfig(Set<String> scanPath) {
        try {
            PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
            for (String path : scanPath) {
                Resource[] resources = pathMatchingResourcePatternResolver.getResources(path);
                for (Resource resource : resources) {
                    try (InputStream inputStream = resource.getInputStream()) {
                        JSONObject fileDetail = JSON.parseObject(inputStream, JSONObject.class);
                        if (!fileDetail.containsKey(ElasticSearchConstant.SETTING_NAME)
                                || !fileDetail.containsKey(ElasticSearchConstant.SETTING)) {
                            throw new GlobalSystemException("setting json file must containsKey:[{},{}]",
                                    ElasticSearchConstant.SETTING_NAME, ElasticSearchConstant.SETTING);
                        }
                        cache.put(fileDetail.getString(ElasticSearchConstant.SETTING_NAME),
                                fileDetail.getJSONObject(ElasticSearchConstant.SETTING).toJSONString());
                    }
                }
            }
        } catch (IOException e) {
            throw new GlobalSystemException(e);
        }
    }

    public String getSetting(String settingName) {
        return cache.get(settingName);
    }
}
